﻿using System.Collections.Generic;
using System.Linq;
using MemoDb.Tests.Model;
using MemoDb.Tests.Model.Collections;
using NUnit.Framework;

namespace MemoDb.Tests
{
    [TestFixture]
    public class QueryTests
    {
        [Test]
        public void QueryInAnotherSession()
        {
            var memo = new Memo()
                            .Map<City>();


            using (var s = memo.CreateSession())
            {
                s.Insert(new City
                             {
                                 Id = 1,
                                 Name = "Buenos Aires"
                             });
                s.Insert(new City
                             {
                                 Id = 2,
                                 Name = "New York"
                             });
                s.Insert(new City
                             {
                                 Id = 3,
                                 Name = "Montevideo"
                             });
                s.Insert(new City
                             {
                                 Id = 4,
                                 Name = "Bogotá"
                             });
                s.Flush();
            }

            using (var s = memo.CreateSession())
            {
                var cities = s.Query<City>().Where(x => x.Name.StartsWith("B"));

                Assert.AreEqual(2, cities.Count());
                Assert.That(cities.Any(x => x.Name == "Buenos Aires"));
                Assert.That(cities.Any(x => x.Name == "Bogotá"));
            }
        }
        private class Parent
        {
            public int Id { get; set; }
            public IList<Child> Children { get; set; }
        }
        private class Child
        {
            public int Id { get; set; }
            public Parent Parent { get; set; }
        }
        [Test]
        public void CircularReferences()
        {
            int id;
            var memo = new Memo(insertByCascadeByDefault: true)
                .Map<Parent>().Map<Child>();

            using (var s = memo.CreateSession())
            {
                var parent = new Parent
                                  {
                                      Children = new List<Child>()
                                  };
                var child = new Child();
                parent.Children.Add(child);
                child.Parent = parent;
                s.Insert(parent);
                id = parent.Id;
                s.Flush();
            }
            using (var s = memo.CreateSession())
            {
                var session = s.Query<Parent>().SingleOrDefault(x => x.Id == id);
                Assert.IsNotNull(session);
            }
        }
    }
}